package com.mkz.jbpm.activiti.impl;

import java.util.List;

import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.mkz.admin.entity.SysUserRole;
import com.mkz.jbpm.activiti.ActIdService;
import com.mkz.jbpm.activiti.base.ActServiceFactory;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * ClassName: ActiIdServiceImpl 
 * @Description: Activiti 身份认证服务实现类
 * @author: KuangJianyu
 * @date: 2020年4月2日
 */
@Slf4j
@Component
public class ActIdServiceImpl extends ActServiceFactory implements ActIdService{
    /**
     * 
     * @Description: 从RBAC同步用户组信息到JBPM模块
     * @param: @param roleCode
     * @param: @param roleName
     * @param: @param urrJson
     * @param: @return   
     * @return: Boolean  
     * @throws:
     * @author: KuangJianyu
     * @date: 2020年4月2日
     */
    public Boolean synGroupInfo(String roleCode, String roleName, String urrJson) {
		Group desGroup = identityService.createGroupQuery().groupId(roleCode).singleResult();
		if(null==desGroup) {
			desGroup = identityService.newGroup(roleCode);
		}
		desGroup.setName(roleName);
		desGroup.setType("assignment");
		identityService.saveGroup(desGroup);
		List<SysUserRole> list = JSONObject.parseArray(urrJson, SysUserRole.class);
		if(CollectionUtil.isNotEmpty(list)) {
			User desUser = null;
			for(SysUserRole temp: list) {
				desUser = identityService.createUserQuery().userId(temp.getUsername()).singleResult();
				if(null==desUser) {
					desUser = identityService.newUser(temp.getUsername());
				}
				desUser.setFirstName(temp.getFullname());
				desUser.setLastName(temp.getFullname());
				desUser.setEmail("syn@xxx.com");
				desUser.setPassword("123456");
				identityService.saveUser(desUser);
				identityService.deleteMembership(temp.getUsername(), roleCode);
				identityService.createMembership(temp.getUsername(), roleCode);
				desUser = null;
			}
		}
		log.info("Group 修改/新增成功...");
    	return true;
    }
    /**
     * @Description: 从RBAC同步用户信息到JBPM模块
     * @param: @param userId
     * @param: @return   
     * @return: Boolean  
     * @throws:
     * @author: KuangJianyu
     * @date: 2020年4月2日
     */
    public Boolean synUserInfo(String userId, String fullname) {
		User desUser = identityService.createUserQuery().userId(userId).singleResult();
		if(null==desUser) {
			desUser = identityService.newUser(userId);
		}
		desUser.setFirstName(fullname);
		desUser.setLastName(fullname);
		desUser.setEmail("syn@xxx.com");
		desUser.setPassword("123456");
		identityService.saveUser(desUser);
		log.info("User 修改/新增成功...");
    	return true;
    }
}